package com.sayice.robotconflict.service;

import com.sayice.robotconflict.common.exception.AppException;
import com.sayice.robotconflict.common.exception.ErrorCode;
import com.sayice.robotconflict.entity.BagEntity;
import com.sayice.robotconflict.entity.RobotEntity;
import com.sayice.robotconflict.game.Game;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 背包业务处理
 *
 * @author shubing
 */
@Slf4j
@Service
public class BagService {
    @Autowired
    private MongoTemplate mongoTemplate;
    
    /**
     * 查询初始机器人
     */
    public List<RobotEntity> queryInitRobots() {
        log.info("BagService queryInitRobots");
        return mongoTemplate.findAll(RobotEntity.class, "init_robot");
    }
    
    /**
     * 查询玩家的机器人
     *
     * @param playerId 玩家ID
     */
    public List<RobotEntity> queryRobots(String playerId) {
        log.info("BagService queryRobots playerId={}", playerId);
        Query query = Query.query(Criteria.where("playerId").is(playerId));
        query.fields().include("robots");
        BagEntity bagEntity = mongoTemplate.findOne(query, BagEntity.class);
        return bagEntity == null ? Collections.emptyList() : bagEntity.getRobots();
    }
    
    /**
     * 查询玩家携带的机器人
     *
     * @param playerId 玩家ID
     */
    public List<RobotEntity> queryCarriedRobots(String playerId) {
        log.info("BagService queryCarriedRobots playerId={}", playerId);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("playerId").is(playerId)),
                Aggregation.unwind("robots"),
                Aggregation.match(Criteria.where("robots.carry").is(true)),
                Aggregation.group().push("robots").as("robots")
        );
        BagEntity bagEntity = mongoTemplate.aggregate(aggregation, "bag", BagEntity.class).getUniqueMappedResult();
        return bagEntity == null ? Collections.emptyList() : bagEntity.getRobots();
    }
    
    /**
     * 添加机器人
     *
     * @param playerId    玩家ID
     * @param robotEntity 机器人
     */
    public void addRobot(String playerId, RobotEntity robotEntity) {
        log.info("BagService addRobot playerId={}, robotEntity={}", playerId, robotEntity);
        if (robotEntity.isCarry() && getCarriedCount(playerId) >= Game.MAX_CARRY) {
            throw new AppException(ErrorCode.CODE_400, "最多携带" + Game.MAX_CARRY + "个机器人");
        }
        Query query = Query.query(Criteria.where("playerId").is(playerId));
        Update update = new Update().push("robots", robotEntity);
        mongoTemplate.updateFirst(query, update, BagEntity.class);
    }
    
    /**
     * 根据下标更新玩家的机器人
     *
     * @param playerId    玩家ID
     * @param index       机器人下标
     * @param robotEntity 新的机器人
     */
    public void updateRobotByIndex(String playerId, int index, RobotEntity robotEntity) {
        log.info("BagService updateRobotByIndex playerId={}, index={}, robotEntity={}", playerId, index, robotEntity);
        Criteria condition = Criteria.where("playerId").is(playerId);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(condition),
                Aggregation.project().and("robots").slice(1, index)
        );
        BagEntity bagEntity = mongoTemplate.aggregate(aggregation, "bag", BagEntity.class).getUniqueMappedResult();
        if (bagEntity == null || bagEntity.getRobots().isEmpty()) {
            return;
        }
        RobotEntity oldRobotEntity = bagEntity.getRobots().get(0);
        if (!oldRobotEntity.isCarry() && robotEntity.isCarry() && getCarriedCount(playerId) >= Game.MAX_CARRY) {
            throw new AppException(ErrorCode.CODE_400, "最多携带" + Game.MAX_CARRY + "个机器人");
        }
        Query query = Query.query(condition);
        Update update = new Update().set("robots." + index, robotEntity);
        mongoTemplate.updateFirst(query, update, BagEntity.class);
    }
    
    /**
     * 根据下标删除玩家的机器人
     *
     * @param playerId 玩家ID
     * @param index    机器人下标
     */
    public void deleteRobotByIndex(String playerId, int index) {
        log.info("BagService deleteRobotByIndex playerId={}, index={}", playerId, index);
        Query query = Query.query(Criteria.where("playerId").is(playerId));
        // 第一步：将元素置 null
        Update update = new Update().unset("robots." + index);
        mongoTemplate.updateFirst(query, update, BagEntity.class);
        // 第二步：将为 null 的元素删除
        update = new Update().pull("robots", null);
        mongoTemplate.updateFirst(query, update, BagEntity.class);
    }
    
    /**
     * 获取玩家携带的机器人数量
     *
     * @param playerId 玩家ID
     */
    private int getCarriedCount(String playerId) {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("playerId").is(playerId)),
                Aggregation.unwind("robots"),
                Aggregation.match(Criteria.where("robots.carry").is(true)),
                Aggregation.group().count().as("sum")
        );
        Document result = mongoTemplate.aggregate(aggregation, "bag", Document.class).getUniqueMappedResult();
        return result == null ? 0 : result.getInteger("sum", 0);
    }
}
